package com.talking.util;

import android.os.StrictMode;

import java.io.File;
import java.util.HashMap;
import java.util.Objects;
import java.util.Set;

import okhttp3.CacheControl;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class Network {
    public static final String BASE_URL = "http://182.61.31.57/";
    public static void post(HashMap<String, String> map, String url, CancelCall cancelCall){
        if (Tools.isWifiProxy()){
            Tools.toast("检测到网路处于代理模式，请不要使用vpn");
        }else{
            CacheControl cacheControl = new CacheControl.Builder().noCache().noStore().build();
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());
            FormBody.Builder body = new FormBody.Builder();
            Set<String> keys = map.keySet();
            for (String key :keys) body.add(key, Objects.requireNonNull(map.get(key)));
            cancelCall.sendCall(getClient().newCall(new Request.Builder().cacheControl(cacheControl).url(BASE_URL + url).post(body.build()).build()));
        }
    }
    public static Request.Builder getFileBuilder(String url){
        return new Request.Builder().url(url);
    }
    public static void upload(String url, File file, Callback callback){
        getClient().newCall(getFileBuilder(BASE_URL+url).post(new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file)).build()).build()).enqueue(callback);
    }
    private static OkHttpClient getClient() {
       return new OkHttpClient().newBuilder().build();
    }
}